package com.heima.article.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.dotos.ApArticleDto;
import com.heima.article.dotos.ApArticleSaveDto;
import com.heima.article.dotos.ArticleHomeDto;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.pojos.ApArticle;
import com.heima.article.pojos.ApArticleConfig;
import com.heima.article.pojos.ApArticleContent;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.constants.WemediaConstants;
import com.heima.constants.WmNewsConstants;
import com.heima.file.service.FileStorageService;
import com.heima.user.model.common.dtos.ResponseResult;
import com.heima.user.model.common.enums.AppHttpCodeEnum;
import com.heima.wemedia.pojos.WmNews;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-26
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    @Override
    public ResponseResult load(ArticleHomeDto dto, short type) {
        Integer size = dto.getSize();

        if (size == null || size == 0) {
            size = 20;
        }
        dto.setSize(size);

        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }

        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }

        if (dto.getTag() == null) {
            dto.setTag("__all__");
        }

        List<ApArticle> list = apArticleMapper.load(dto, type);


        return ResponseResult.okResult(list);
    }

    @Override
    //开启事物
    @Transactional
    public ResponseResult saveApp(ApArticleSaveDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        apArticleMapper.insert(apArticle);

        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsDelete(WemediaConstants.WM_NEWS_NONE_IMAGE);
        apArticleConfig.setIsDown(WemediaConstants.WM_NEWS_NONE_IMAGE);
        apArticleConfig.setIsComment(dto.getIsComment());
        apArticleConfig.setIsForward(dto.getIsForward());
        apArticleConfigMapper.insert(apArticleConfig);

        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(dto.getContent());
        apArticleContentMapper.insert(apArticleContent);

        return ResponseResult.okResult(apArticle.getId());
    }


   @KafkaListener(topics = WmNewsConstants.WM_NEWS_TOPIC)
    public void receiveMsg(ConsumerRecord<String, String> record, Consumer<String,String> consumer) {

        String value = record.value();
        log.info("接收到消息：{}",value);
        WmNews wmNews = JSONArray.parseObject(value, WmNews.class);


        //修改文章配置
        if (wmNews != null && wmNews.getId() != null) {
            LambdaQueryWrapper<ApArticleConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleConfig::getArticleId,wmNews.getArticleId());
            ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(queryWrapper);
            //判断是上架状态还是下架状态
            if (wmNews.getEnable().equals(WmNews.Status.SUBMIT.getCode())) {
                //上架
                apArticleConfig.setArticleId(wmNews.getArticleId());
                apArticleConfig.setIsComment(WmNews.Status.SUBMIT.getCode());
                apArticleConfig.setIsForward(WmNews.Status.SUBMIT.getCode());
                apArticleConfig.setIsDown(WmNews.Status.NORMAL.getCode());
                apArticleConfigMapper.updateById(apArticleConfig);
                log.info("上架成功");
            }
            if (wmNews.getEnable().equals(WmNews.Status.NORMAL.getCode())) {
                //下架
                apArticleConfig.setArticleId(wmNews.getArticleId());
                apArticleConfig.setIsComment(WmNews.Status.NORMAL.getCode());
                apArticleConfig.setIsForward(WmNews.Status.NORMAL.getCode());
                apArticleConfig.setIsDown(WmNews.Status.SUBMIT.getCode());
                apArticleConfigMapper.updateById(apArticleConfig);
                log.info("下架成功");
            }
        }
        consumer.commitAsync();
    }

    @KafkaListener(topics = WmNewsConstants.WM_NEWS_AUTO_TOPIC)
    public void freemarker(ConsumerRecord<String, String> record, Consumer<String,String> consumer) throws Exception {
        String value = record.value();
        WmNews wmNews = JSONArray.parseObject(value, WmNews.class);
        //获取文章内容
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, wmNews.getArticleId());
        ApArticleContent articleContent = apArticleContentMapper.selectOne(queryWrapper);

        //通过freemarker生成html文件
        Template template = configuration.getTemplate("article.ftl");

        //模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(articleContent.getContent()));
        //生成静态页面
        template.process(map, new FileWriter("D://ApArticle.html"));

        //把html文件上传到minio中
        String path = fileStorageService.uploadHtmlFile("", "aaa.html", new FileInputStream("D://ApArticle.html"));

        //更新文章的静态地址
        ApArticle apArticle = new ApArticle();
        apArticle.setId(articleContent.getArticleId());
        apArticle.setStaticUrl(path);

        apArticleMapper.updateById(apArticle);

    }
    }
